package com.richly.iot;

import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: l_y
 * @Date: 2022/6/16 17:30
 * @FileName: WrapperAnalysis
 * @Description: 解析IotWrapper
 */
@NoArgsConstructor
public class IotWrapperAnalysis {

    private static final String SPACE = " ";
    private static final String AND = " and ";

    public static String analysisToSql(IotWrapper wrapper, String tableName) {
        StringBuilder builder = new StringBuilder();
        String sql = "";
        builder.append("select * from ").append(tableName).append(SPACE);

        if (!CollectionUtils.isEmpty(wrapper.getParams()) || !CollectionUtils.isEmpty(wrapper.getGt())
                || !CollectionUtils.isEmpty(wrapper.getLt())) {
            builder.append("where").append(SPACE);
            if (!CollectionUtils.isEmpty(wrapper.getParams())) {
                wrapper.getParams().forEach((k, v) -> {
                    builder.append(k).append(" = ").append(castData(v)).append(SPACE).append(AND);
                });
            }
            if (!CollectionUtils.isEmpty(wrapper.getGt())) {
                wrapper.getGt().forEach((k, v) -> {
                    builder.append(k).append(" > ").append(castData(v)).append(SPACE).append(AND);
                });
            }
            if (!CollectionUtils.isEmpty(wrapper.getLt())) {
                wrapper.getLt().forEach((k, v) -> {
                    builder.append(k).append(" < ").append(castData(v)).append(SPACE).append(AND);
                });
            }
            sql = builder.substring(0, builder.lastIndexOf(AND));
        } else {
            sql = builder.toString();
        }
        return sql;
    }

    private static String castData(Object o) {
        if (o instanceof String) {
            return (String) o;
        }
        if (o instanceof BigDecimal) {
            return o.toString();
        }
        if (o instanceof Date) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.format((Date) o);
        }
        if (o instanceof Integer) {
            return o.toString();
        }
        return null;
    }

    ;

}
